package com.hkemmm.db;

import org.apache.commons.dbcp2.BasicDataSource;

import javax.sql.DataSource;

//单例模式，在程序的运行周期中只存在一个该对象
public class DBCPDataSource {
    //数据源
    private static DataSource dataSource;

    private DBCPDataSource(){

    }

    //synchronized保证线程安全，保证多线程调用时不会同时调用该方法
    public static synchronized DataSource getDataSource(){
        if(dataSource == null){
            //服务器访问路径
            String strURLMysql8 = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong&allowPublicKeyRetrieval=true";

            //数据库驱动
            String strDriverMysql8 = "com.mysql.cj.jdbc.Driver";

            String userName = "root";
            String userPsw = "Hkemmmm";

            //设置数据库连接信息
            BasicDataSource basicDataSource = new BasicDataSource();
            basicDataSource.setUrl(strURLMysql8);
            basicDataSource.setDriverClassName(strDriverMysql8);
            basicDataSource.setUsername(userName);
            basicDataSource.setPassword(userPsw);


            dataSource = basicDataSource;
        }

        return dataSource;
    }
}
